package com.wzxy.medical_backed.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzxy.medical_backed.entity.Insured;
import com.wzxy.medical_backed.entity.Result;
import com.wzxy.medical_backed.service.InsuredService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/insureds")
public class InsuredController {

    @Autowired
    private InsuredService insuredService;

    @GetMapping("/getall")
    public Result getAll(@RequestParam(required = false) String keyword,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size) {
        QueryWrapper<Insured> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("insured_name", keyword).or().like("card_id", keyword);
        }
        IPage<Insured> insuredPage = insuredService.page(new Page<>(page, size), queryWrapper);
        return new Result("查询成功", insuredPage, 200);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Insured insured) {
        Insured one = insuredService.getOne(new QueryWrapper<Insured>().eq("id", insured.getId()));
        if (one != null) {
            return new Result("用户已存在", null, 200);
        } else {
            return new Result("添加成功", insuredService.save(insured), 200);
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        return new Result("删除成功", insuredService.removeById(id), 200);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Insured insured) {
        return new Result("修改成功", insuredService.updateById(insured), 200);
    }
    @GetMapping("/all")
    public Result<List<Insured>> getAllInsured() {
        return Result.success(insuredService.list());
    }
//    @GetMapping("/getinsured/{cardId}")
//    public Result getInsured(@PathVariable("cardId") String cardId) {
//        return new Result("查询成功", insuredService.getOne(new QueryWrapper<Insured>().eq("card_id", cardId)), 200);
//    }
//    // ... existing code ...
//    @GetMapping("/search")
//    public Result search(@RequestParam String keyword) {
//        QueryWrapper<Insured> wrapper = new QueryWrapper<>();
//        wrapper.like("insured_name", keyword).or().like("card_id", keyword);
//        return new Result("查询成功", insuredService.list(wrapper), 200);
//    }
// ... existing code ...
}

